import router from "@/router/index"
import store from "@/store"

router.beforeEach((to,from, next)=>{
    const whiteList=['/login']//白名单
    let token=store.getters.GET_TOKEN;
    let hasRoute = store.state.hasRoute;
    let menuList = store.getters.GET_MENULIST;
    if(token) {
        if (!hasRoute) {
            bindRouter(menuList);
            store.commit('SET_ROUTER_STATE', true);
        }

        next();
    } else {
        if(whiteList.includes(to.path)){
            next();
        }else{
            next("/login");
        }
    }
})

// 动态绑定路由
const bindRouter = (menuList) => {
    let newRoutes = router.options.routes;
    menuList.forEach(menu=>{
        if (menu.children) {
            menu.children.forEach(m=>{
                let router = menuToRouter(m,menu.mName);
                if (router) {
                    newRoutes[0].children.push(router)
                }
            })
        }
    })

    // 加载到路由中
    newRoutes.forEach(route=>{
        router.addRoute(route);
    })

}

// 菜单对象转换成路由对象
const menuToRouter = (menu, parentName) => {
    if (!menu.mComponent){
        return null;
    } else {
        let router = {
            name:menu.mName,
            path:menu.mPath,
            meta:{
                parentName: parentName
            }
        }

        router.component = () => import('@/views/'+menu.mComponent+'.vue');
        return router;
    }
}